#coding=utf-8
from uliweb import expose,functions,settings

#可以省略直接引用
from uliweb import request, error, redirect, Response

from sqlalchemy import or_
import uuid
import time
import os
import base64
import urllib2

def __begin__():
    """
    用户验证 权限验证
    """
    from uliweb import functions
    functions.require_login()
    return functions.has_role()

@expose('/ueditor')
class Ueditor(object):
    """
    用于百度html编辑器
    """
    def __init__(self):
        from uliweb.orm import get_model
        self.applicationtypemodel = get_model('applicationtype')

    def applicationtypedocedit(self):
        """
        文档编辑
        """

        _id = request.GET.get("id")
        flag = request.GET.get("flag")
        
        ormdata = functions.get_object(self.applicationtypemodel, _id, cache=True, use_local=True)

        return {"id":_id,
                "content":ormdata.applicationtype_dep_doc,
                "msg":str(ormdata.applicationtype_name) + "----部署文档"}
    
    def applicationtypedocsave(self):
        """
        保存文档编辑
        """

        _id = request.POST.get("id")
        editor = request.POST.get("editor")
        
        ormdata = functions.get_object(self.applicationtypemodel, _id, cache=True, use_local=True)
        ormdata.applicationtype_dep_doc = editor
        
        try:
            ormdata.save()
        
            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"添加文档失败,请联系管理员"})
        
    def applicationtypedocshow(self):
        """
        查看文档编辑
        """

        _id = request.GET.get("id")
        flag = request.GET.get("flag")

        ormdata = functions.get_object(self.applicationtypemodel, _id, cache=True, use_local=True)
        
        return {"content":ormdata.applicationtype_dep_doc,
                "msg":str(ormdata.applicationtype_name) + "----部署文档"}


#############################################################################################################

    def _myuploadfile(self,fileObj, source_pictitle, source_filename,tmpfile=False, fileorpic='pic'):
        """ 
        一个公用的上传文件的处理 
        """
        myresponse=""
        if fileObj:
            #将文件名编码成utf-8,默认gbk
            filename = source_filename.decode('utf-8', 'ignore')

            #得到文件扩展名
            fileExt = filename.split('.')[1]
            #通过uuid生成新文件名
            new_filename = str(uuid.uuid1()) + '.' + fileExt
            #年月日目录
            subfolder = time.strftime("%Y%m%d")

            #完整的保存路径
            if tmpfile:
                #存放零时文件
                #获取settings.ini中上传的目录
                up_path = settings['UPLOAD']['TMP_PATH']
                full_upload_dir = os.path.join(up_path,subfolder)
            else:
                up_path = settings['UPLOAD']['TO_PATH']
                full_upload_dir = os.path.join(up_path,subfolder)
            #判断目录是否存在
            if not os.path.exists(full_upload_dir):
                os.makedirs(full_upload_dir)
                
            #完整的文件保存路径
            filepath = os.path.join(full_upload_dir,new_filename)

            if fileExt.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png',"rar" ,"doc" ,"docx","zip","pdf","txt","swf","wmv"):

                destination = open(filepath, 'wb+')
                destination.write(fileObj.stream.read())            
                destination.close()
    
                real_url = up_path.split('.')[1] + '/' + subfolder + '/' + new_filename       
                myresponse = "{'original':'%s','url':'%s','title':'%s','state':'%s'}" % (source_filename, real_url, source_pictitle, 'SUCCESS')
        return myresponse    

    def imageUp(self): 
        """ 
        上传图片 
        接收数据
        ImmutableMultiDict([('pictitle', u'sadadsd'), 
                            ('fileNameFormat', u'{time}{rand:6}'), 
                            ('Filename', u'20140214112158530_easyicon_net_16.png'), 
                            ('Upload', u'Submit Query'), 
                            ('dir', u'uploads'), 
                            ('fileName', u'20140214112158530_easyicon_net_16.png')])
        """
               
        
        #得到上传文件流
        fileObj = request.FILES.get('upfile', None)
        #文件描述 gbk编码
        source_pictitle = request.POST.get('pictitle','')
        #文件名字
        source_filename = request.POST.get('fileName','')
        if source_filename == '':
            source_filename = request.POST.get('Filename','')
        
        response = Response()  
        myresponse = self._myuploadfile(fileObj, source_pictitle, source_filename, fileorpic='pic')
        response.write(myresponse)
        return response


    def fileUp(self): 
        """
        上传文件
        接收数据
        ImmutableMultiDict([('fileNameFormat', u'{time}{rand:6}'), 
                            ('PHPSESSID', u'<?php echo session_id(); ?>'), 
                            ('Upload', u'Submit Query'), 
                            ('Filename', u'404.zip')])
        """ 

        fileObj = request.FILES.get('upfile', None)
        #这个值不存在
        source_pictitle = request.POST.get('pictitle','')
        #文件名
        source_filename = request.POST.get('Filename','')    
        response = Response()  
        myresponse = self._myuploadfile(fileObj, source_pictitle, source_filename,'file')
        response.write(myresponse)
        return response


    def scrawlUp(self):
        """
        涂鸦文件
        
        文件内容使用base64加密传输
        """

        param = request.GET.get("action",'')

        fileType = [".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"];

        subfolder = time.strftime("%Y%m%d")
        
        if  param=='tmpImg':
            #背景图上传
            fileObj = request.FILES.get('upfile', None)   
            source_pictitle = request.POST.get('pictitle','')  
            source_filename = request.POST.get('fileName','')
            
            if source_filename == '':
                source_filename = ''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(16))) + '.jpg'
                    
            response = Response()  
            myresponse = self._myuploadfile(fileObj, source_pictitle, source_filename,tmpfile=True, fileorpic='pic')           

            myresponsedict=eval(myresponse)
            url=myresponsedict.get('url','')
            #url = 'localhost' + str(url)
            
            #print "url====>",url
            response.write("<script>parent.ue_callback('%s','%s')</script>" %(url,'SUCCESS'))
            return response
        else:
            #========================base64上传的文件======================= 
            base64Data = request.POST.get('content','')
            #获取settings.ini中上传的目录
            full_upload_dir = os.path.join(settings['UPLOAD']['TO_PATH'],subfolder)
            
            if not os.path.exists(full_upload_dir):
                os.makedirs(full_upload_dir)
                
            file_name = str(uuid.uuid1()) + '.' + 'png'
            
            phisypath = os.path.join(full_upload_dir,file_name)
            f=open(phisypath,'wb+')
            f.write(base64.decodestring(base64Data))
            f.close()
            response=Response()
            response.write("{'url':'%s',state:'%s'}" % ('/uploads/' + subfolder + '/' + file_name,'SUCCESS'));
            return response



    def getRemoteImage(self):
        """
        把远程的图抓到本地,爬图
        """
            
        #====get request params=================================
        #得到图片url
        urls = str(request.POST.get("upfile"));
        #ueditor的分隔符
        urllist=urls.split("ue_separate_ue")
        outlist=[]
        #====request params end=================================
        fileType = [".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"]
        for url in urllist:
            
            #防止文件重名覆盖
            file_name = str(uuid.uuid1())
            subfolder = time.strftime("%Y%m%d")
            #获取settings.ini中上传的目录
            full_upload_dir = os.path.join(settings['UPLOAD']['TO_PATH'],subfolder)
            
            if not os.path.exists(full_upload_dir):
                os.makedirs(full_upload_dir)
                
            fileExt=""
            for suffix in fileType:
                if url.endswith(suffix):
                    fileExt=suffix
                    break;
            if fileExt=='':
                continue
            else:
                #文件名 fileExt是完整的扩展名.jpg,包含.
                new_filename = file_name + fileExt

                #文件完整路径
                phisypath = os.path.join(full_upload_dir,new_filename)
                #读取远程文件
                piccontent= urllib2.urlopen(url).read()
                
                picfile=open(phisypath,'wb')
                picfile.write(piccontent)
                picfile.close()
                
                outlist.append('/uploads/' + subfolder + '/' + new_filename)
                
        outlist="ue_separate_ue".join(outlist)

        response=Response()
        myresponse="{'url':'%s','tip':'%s','srcUrl':'%s'}" % (outlist,'成功',urls)
        response.write(myresponse);
        return response

    def _listdir(self,path,filelist):
        """ 
        递归 得到所有图片文件信息
        """

        if os.path.isfile(path):
            return '[]' 
        allFiles=os.listdir(path)
        retlist=[]
        for cfile in allFiles:
            filepath=(path+os.path.sep+cfile).replace("\\","/").replace('//','/')
            
            if os.path.isdir(filepath):
                self._listdir(filepath,filelist)
            else:
                if cfile.endswith('.gif') or cfile.endswith('.png') or cfile.endswith('.jpg') or cfile.endswith('.bmp'):
                    #filelist.append(filepath.replace(path,'/uploads/').replace("//","/"))
                    #获取左边第一个.
                    index = filepath.index('.')
                    #获取第一个.后面的内容
                    filepath = filepath[index + 1:]                    
                    filelist.append(filepath)


    def imageManager(self):
        """ 
        图片在线管理 
        """
        #保存图片列表
        filelist=[]
        #获取上传目录
        phisypath = settings['UPLOAD']['TO_PATH']
        #读取图片
        self._listdir(phisypath,filelist)
        #百度ueditor的图片分隔符
        imgStr="ue_separate_ue".join(filelist)
        response=Response()
        response.write(imgStr)     
        return response


    def getMovie(self):
        """ 
        获取视频数据的地址 
        """
        content ="";   
        searchkey = request.POST.get("searchKey");
        videotype = request.POST.get("videoType");
        try:        
            url = "http://api.tudou.com/v3/gw?method=item.search&appKey=myKey&format=json&kw="+ searchkey+"&pageNo=1&pageSize=20&channelId="+videotype+"&inDays=7&media=v&sort=s";
            content=urllib2.urlopen(url).read()
        except Exception,e:
            pass
        response=Response()  
        response.write(content);
        return response